<!-- 订单 -->
<template>
  <div class="container order">
    <div class="top">
      <div class="return_box" @click="returnBack">
        <span>返回</span>
      </div>
    </div>
    <div class="body">
      <div class="order_item base_info">
        <div class="title_box">
          <h4 class="title">基本信息</h4>
          <div class="order_code" v-if="orderCode">订单编号:{{orderCode}}</div>
        </div>

        <div class="card complete_info" v-if="studentInfo" @click="toUserInfo">
          <span>{{studentInfo.studentName}}</span>
          <div>
            <span style="margin-right: 10px;">{{studentInfo.linkPhone}}</span>
            <i class="icon_right2"></i>
          </div>
        </div>
        <div class="card uncomplete_info" v-else @click="toUserInfo">
          <span>请完善基本信息</span>
          <div>
            <i class="icon_warning"></i>
            <i class="icon_right"></i>
          </div>
        </div>
        
      </div>
      <div class="order_item">
        <h4 class="title">购买课程</h4>
        <ul class="class_list card">
          <li class="class_item">
            <div class="class_info_box">
              <div class="class_img">
                <img src="../assets/img/class_img.png" alt="">
              </div>
              <div class="class_info">
                <div class="class_name">{{productInfo.productName}}</div>
                <div class="class_hour">{{productInfo.schoolName}}</div>
                <div class="price">
                  <span class="original_price">￥{{productInfo.productPrice}}</span>
                  <span class="discount_price">折后价￥{{computedPayPrice}}</span>
                </div>
              </div>
            </div>
            
          </li>
        </ul>
      </div>
      <div class="order_item">
        <h4 class="title">优惠信息</h4>
        <div class="card discount_info">
          <van-cell title="优惠类型" is-link :value="discountInfo.remarkDiscount" @click="changeDiscount" />
          <!-- <van-cell title="优惠描述"  value="" /> -->
          <van-cell title="优惠力度"  :value="discountInfo.discountPrice" v-if="!doNotDiscount" />
        </div>
      </div>
      <div class="order_item">
        <h4 class="title">支付方式</h4>
        <div class="card pay_methods">
          <van-cell title="缴费类型"  value="全款" />
          <van-radio-group v-model="payMethod" :disabled="this.payStep != '1'">
            <van-cell-group>
              <van-cell title="微信" icon="icon_wx" clickable @click="changePayMethod('1')">
                <!-- <i slot="left-icon">11</i> -->
                <van-radio slot="right-icon"  checked-color="#FFD33D" name="1" />
              </van-cell>
              <!-- <van-cell title="支付宝" icon="icon_zfb" clickable @click="changePayMethod('2')">
                <van-radio slot="right-icon"  checked-color="#FFD33D" name="2" />
              </van-cell> -->
            </van-cell-group>
          </van-radio-group>
        </div>
      </div>
    </div>

    <div class="bottom">
      <div class="discount_box" v-if="discountInfo.discountId">
        <span>原价￥{{productInfo.productPrice}}</span>
        <span class="discount_type">{{discountInfo.remarkDiscount}}</span>
        <span class="discount_price"><span v-if="discountInfo.discountPrice">-￥</span>{{discountInfo.discountPrice}}</span>
      </div>
      <div class="total_box">
        <div>
          <!-- 合计: <span class="total_price">￥{{productInfo.payPrice}}</span> -->
          合计: <span class="total_price">￥{{computedPayPrice}}</span>
        </div>

        <div class="pay_box"> 
          <span class="order_status" v-if="payStep == '2'">待支付</span>
          <!-- <div class="" v-if="payStep == '2'" @click="payStep = '1'" style="margin-right: 10px">返回修改</div> -->
          <!-- <div class="btn btn_order" v-if="payStep == '1'" @click="prewOrder">预览</div> -->
          <div class="btn btn_order" v-if="payStep == '1'" @click="generateOrder">生成订单</div>
          <div class="btn btn_order" v-if="payStep == '2'" @click="payment">支付</div>
        </div>
        
      </div>
    </div>

    <div class="popup">
      <van-popup v-model="showBottomArea" round position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          title="选择优惠"
          value-key="remarkDiscount"
          :columns="discountList"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
      </van-popup>
    </div>
  </div>
</template>


<script>
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("adminBasic");
export default {
  name: 'order',
  data() {
    return {
      payMethod: '1',
      payStep: '1',
      previewOrder: false,
      showBottomArea: false,
      openId: '',
      orderCode: '',
      createByObj: {},
      tnData: {},
      doNotDiscount: false,

      productInfo: {},
      studentInfo: {},

      schoolList: [],
      schoolName: '',

      discountList: [],
      discountInfo: {
        discountId: '',
        remarkDiscount: '请选择',
        discountRemark: '',
        discountPrice: '',
      },

      formData: {
        studentName: '',
        sex: '',
        linkPerson: '',
        linkPhone: '',
        wechat: '',
        idCard: '',
        schoolId: '',
        remark: '',
        employeesId: '',
        paymentType: '2',
        paymentMethod: '',
        paymentPrice: '',
        productPrice: '',
        discountList: [
          {
            discountType: '',
            remarkDiscount: '',
            discountPrice: '',
            discountMethod: '',
            productId: '',
            subjectDiscount: '',
          },{
            discountType: '',
            remarkDiscount: '',
            discountPrice: '',
            discountMethod: '',
            productId: '',
            subjectDiscount: '',
          }
        ],
        bmOrderStagesList: [
          
        ],
      },
    }
  },

  created() {
    this.openId = localStorage.getItem('openId');

    if(this.$route.query.continue == 1) {
      console.log(this.$route.query)
      this.initDataByOrderCode(this.$route.query.orderCode);
    }else{
      this.initProductData();
      this.initStudentData();
    }

    this.insertPvUv();

    this.createByObj = JSON.parse(localStorage.getItem('createByObj'))
    
    // alert('经办人id：' + this.createByObj.createBy);
    // alert('经办人Name：' + this.createByObj.createByName);
  },

  methods: {
    ...mapActions([
      "formGet",
      "post"
    ]),

    insertPvUv() {
      this.post({
        API: 'insertPvUv',
        data: {
          openId: this.openId,
          pageName: '订单页',
          pageType: 'order'
        }
      }).then(res => {

      })
    },

    initDataByOrderCode(orderCode) {
      this.formGet({
        API: 'queryByOrderCode',
        data: {
          orderCode: orderCode
        }
      }).then(res => {
        // console.log(this.openId);
        this.payStep = 2;
        this.studentInfo = res.bmOrderStudent;
        this.productInfo = res.bmSchoolOpenOut;
        this.discountInfo = res.bmOrderHistoryExitList[0]
        this.orderCode = res.bmOrder.orderCode;
        this.paymentMethod = res.bmOrder.paymentMethod;
      }).catch(err => {
        this.$toast(err);
      })
    },

    changeDiscount() {
      if(this.payStep != '1') {
        return
      }
      this.showBottomArea = true;
    },

    onConfirm(value, index) {
      // console.log(`当前值：${value}, 当前索引：${index}`)
      console.log(value)
      if(value.remarkDiscount == '不使用优惠' || value.remarkDiscount == '暂无优惠') {
        this.doNotDiscount = true;
      }else{
        this.doNotDiscount = false;
      }
      // this.formData.sexLabel = this.sexList[index].sexLabel;
      if(value.remarkDiscount) {
        this.discountInfo.discountId = value.discountId;
        this.discountInfo.remarkDiscount = value.remarkDiscount;
        this.discountInfo.discountPrice = value.discountPrice;
      }else{
        this.doNotDiscount = true;
      }
      this.showBottomArea = false;
    },
    onCancel() {
      this.showBottomArea = false;
    },


  
    

    // 预览订单   需求取消
    // prewOrder() {
    //   if(!this.studentInfo) {
    //     this.$toast('请完善基本信息');
    //     return;
    //   }
    //   this.payStep = '2';
    // },

    generateOrder() {
      
      this.initOrderCode();
    },

    initOrderCode() {
      this.formGet({
        API: 'queryCanUseOrderCode',
        data: {
          schoolId: this.$route.query.schoolId
        }
      }).then(res => {
        this.orderCode = res
        this.insertOrder();
      }).catch(err => {

      })
    },

    // 生成订单后入库
    insertOrder() {
      // let data = this.formData;
      let data = {};
      Object.assign(data, this.formData);

      let productIdList = [];
      let productId = '';
      let productPrice = 0;

      
      data.personName = '';
      data.createBy = this.createByObj.createBy;
      data.createByName = this.createByObj.createByName;
      data.studentId = this.studentInfo.studentId;
      data.schoolId = this.$route.query.schoolId;
      data.schoolName = this.productInfo.schoolName;
      data.productId = this.productInfo.productId;
      data.orderCode = this.orderCode;
      data.productPrice = this.productInfo.productPrice;
      data.paymentPrice = this.productInfo.discountPrice;
      // data.paymentType = '2';  // 全款
      // paymentType == 10  待支付状态 传10；
      data.paymentType = '10';
      data.paymentMethod = this.payMethod;  // 微信1 or 支付宝2
      data.employeesId = '';

      data.bmOrderHistory = this.productInfo;    // 课程信息
      // data.bmOrderHistory.associationMode = ''
      // data.bmOrderHistory.associationSubjectPackageId = ''


      data.bmOrderHistoryExitList = []
      this.discountList.forEach(item => {
        if(item.discountId) {
          data.bmOrderHistoryExitList.push(item);
        }
      })


      data.bmOrderHistory.standardPrice = this.productInfo.discountPrice.toString();
      data.bmOrderHistory.statisticsPrice = this.productInfo.productPrice;


      console.log(data);

      // return false;

      this.post({
        API: 'insert',
        data: data
      }).then(res => {
        console.log(res);
        this.payStep = 2;
      }).catch(err => {
        this.$toast(err);
      })
    },

    // 支付后，修改订单状态
    updatePaymentStatus() {
      let data = {
        orderCode: this.orderCode,
        paymentStatus: '2',
        studentId: this.studentInfo.studentId,
        bmOrderHistory: this.productInfo,
      }

      data.bmOrderHistory.standardPrice = this.productInfo.discountPrice.toString();
      data.bmOrderHistory.statisticsPrice = this.productInfo.productPrice;
      
      this.post({
        API: 'updatePaymentStatus',
        data: data
      }).then(res => {
        this.$router.push({
          name: 'mine',
          params: {
            openId: this.openId
          }
        })
      })
    },

    // 支付
    payment() {
      let data = {
        orderCode: this.orderCode,
        productName: this.productInfo.productName,
        paymentMethod: this.payMethod,
        paymentPrice: this.computedPayPrice.toString(),   // 单位 元
        openId: this.openId,
      }

      console.log(data);

      this.post({
        API: 'nowPayForGZH',
        data: data
      }).then(res => {
        if(res.tn) {
          let tnArr = res.tn.split("&");

          for (let j = 0; j < tnArr.length; j++) {
            let params = tnArr[j];
            let index = params.indexOf("=");
            let paramName = params.substring(0,index);
            let paramValue = params.substring(index+1);

            this.tnData[paramName] = paramValue
          }

          window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
            appId: this.tnData.wxAppId,
            timeStamp: this.tnData.timeStamp,
            nonceStr: this.tnData.nonceStr,
            package: `prepay_id=${this.tnData.prepay_id}`,
            signType: this.tnData.signType,
            paySign: this.tnData.paySign,
          }, (res) => {

            // 支付成功，更改订单状态
            if(res.err_msg == "get_brand_wcpay_request:ok"){
              console.log('支付成功')
              this.updatePaymentStatus();
            }

          })
        }else{
          this.$toast(res.responseMsg);
        }
        
      }).catch(err => {
        this.$toast(err);
      })

    },

    

    changePayMethod(index) {
      if(this.previewOrder) {
        return
      }else{
        this.payMethod = index;
      }
    },
    
    
    

    initStudentData() {
      let data = {
        openId: this.openId
      }

      this.formGet({
        API: 'queryStudentByOpenId',
        data: data
      }).then(res => {
        console.log(res);
        if(res) {
          res.sex == 1 ? res.sex = '男' : res.sex = '女';
          this.studentInfo = res;
        }else{
          this.studentInfo = null;
        }
      }).catch(err => {
        this.$toast(err);
      })
    },

    initProductData() {
      let data = {
        productId: this.$route.query.productId,
        schoolId: this.$route.query.schoolId,
      }

      this.formGet({
        API: 'queryOnlineProductDetails',
        data: data
      }).then(res => {
        this.productInfo = res;
        this.productInfo.schoolId = this.$route.query.schoolId;
        
        this.discountList = res.bmSchoolOpenList;

        let noDiscount = null
        if(res.bmSchoolOpenList.length == 1 && res.bmSchoolOpenList[0].remarkDiscount == '') {
          noDiscount = {
            discountPrice: '',
            remarkDiscount: '暂无优惠',
          }
        }else{
          noDiscount = {
            discountPrice: '',
            remarkDiscount: '不使用优惠',
          }
        }
        this.discountList.unshift(noDiscount)
        

        this.discountList.forEach(item => {
          if(item.remark == '1') {
            this.discountInfo = item;
          }
        })
      }).catch(err => {
        this.$toast(err);
      })
    },

    returnBack() {
      this.$router.go(-1);
    },

    toUserInfo() {
      if(this.payStep != 1) {
        return;
      }
      this.$router.push({
        name: 'userInfo',
        params: {
          openId: this.openId
        }
      })
    },
  },

  computed: {
    computedPayPrice() {
      return (Number(this.productInfo.productPrice) - Number(this.discountInfo.discountPrice)).toFixed(2);
    }
  }
}
</script>


<style scoped>
.top {
  height: 1.173333rem;
  background: #FFD33D;
  position: relative;
}

.order .body {
  padding: .226667rem .346667rem;
  box-sizing: border-box;
  padding-bottom: 2.426667rem;
}
.order .body .order_item {
  margin-bottom: .266667rem;
}
.order .body .order_item .title {
  font-size: .4rem;
  color: #303133;
  margin-bottom: .28rem;
}

.base_info .title_box {
  display: flex;
  justify-content: space-between;
}
.base_info .order_code {
  font-size: .373333rem;
  color: #999999;
}
.uncomplete_info span {
  color: #FF6D6D;
  font-size: .373333rem;
}
.complete_info span {
  font-size: .373333rem;
}
.base_info .card {
  height: 1.266667rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 .44rem;
}
.base_info .card > div {
  display: flex;
  align-items: center;
}
.icon_warning {
  margin-right: .36rem;
}
.card {
  background: #fff;
  border-radius: .293333rem;
  overflow: hidden;
}

.class_info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: .4rem .2rem
}
.class_info .class_name {
  font-weight: bold;
}
.class_item {
  padding: .253333rem .32rem;
  box-sizing: border-box;
}
.class_info_box {
  margin-top: 0;
}
.class_info .discount_price  {
  display: block;
}
.bottom {
  position: absolute;
  bottom: 1.306667rem;
  width: 100%;
}
.bottom .discount_box {
  background: #FFF1C1;
  height: 1.066667rem;
  color: #303133;
  font-size: .373333rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 .533333rem 0 .453333rem;
  box-sizing: border-box;
}

.bottom .discount_type {
  margin-right: auto;
  margin-left: .8rem;
}
.bottom .discount_price {
  color: #FF6D6D;
}

.bottom .total_box {
  background: #fff;
  height: 1.426667rem;
  padding: 0 .24rem 0 .413333rem;
  box-sizing: border-box;
  font-size: .373333rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.bottom .total_price {
  color: #FF6D6D;
  font-weight: bold;
}
.bottom .pay_box {
  display: flex;
  align-items: center;
}
.bottom .btn_order {
  width: 2.293333rem;
  height: .8rem;
}
.bottom .order_status {
  color: #FF6D6D;
  font-weight: bold;
  margin-right: .266667rem;
}

.icon_right2 {
  display: inline-block;
  width: .186667rem;
  height: .32rem;
  background: url('../assets/img/icon_back.png');
  background-size: contain;
  transform: rotate(180deg);
}

</style>
